<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { Search } from '@element-plus/icons-vue';
import { $DoctorList, $DeleteDoctor, $InsertDoctor, $UpdateDoctor } from '@/api/doctor';

// 医生表格
const searchQuery = ref(''); //搜索关键字
const selectAll = ref(false); //全选按钮
const selected = ref([]); //已选中的

//获取医生数据
const doctor = ref([]);
const type = (["内科", "外科", "儿科"])

onMounted(async () => {
    $DoctorList().then(res => {
        doctor.value = res.data;
    })
})

// 全选按钮
const toggleSelectAll = () => {
    if (selectAll.value) {
        // 获取当前显示的所有医生账号
        const allIds = doctor.value.map(doctor => doctor?.id);
        // 合并已选中的和当前显示的，避免重复
        selected.value = [...new Set([...selected.value, ...allIds])];
    } else {
        // 取消选中当前显示的所有医生
        const displayedIds = doctor.value.map(doctor => doctor?.id);
        selected.value = selected.value.filter(id => !displayedIds.includes(id));
    }
};

// 过滤搜索
const filteredDoctor = computed(() => {
    const query = searchQuery.value.toLowerCase();
    if (!query) return doctor.value;

    return doctor.value.filter(doctor =>
        doctor.id?.toString().includes(query) ||
        doctor.name.includes(query) ||
        doctor.position.includes(query) ||
        type[doctor.department].includes(query) ||
        doctor.introduction.includes(query) ||
        doctor.good.includes(query));
})

// 当选中项数量等于当前显示的学生数量时，自动勾选全选复选框
watch(selected, (newVal) => {
    selectAll.value = newVal.length === filteredDoctor.value.length && filteredDoctor.value.length > 0
})

//添加弹框控制
const isAdd = ref(false);
const openAdd = () => { isAdd.value = true };
const closeAdd = () => { isAdd.value = false };
const confirmAdd = () => {
    console.log('添加成功');
    isAdd.value = false;
    isAddP.value = true;
};
const isAddP = ref(false);
const closeAddP = () => { isAddP.value = false };
const confirmAddP = async (formEl: FormInstance | undefined, ruleForm: RuleForm) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            $InsertDoctor(ruleForm).then(res => {
                if (res.code == 0) {
                    ElMessage({
                        message: '添加成功',
                        type: 'success',
                    })
                    $DoctorList().then(res => {
                        doctor.value = res.data;
                    })
                    isAddP.value = false
                } else {
                    ElMessage({
                        message: '添加失败',
                        type: 'error',
                    })
                }
            })
        } else {
            console.log('传输失败', fields)
        }
    })
};

//编辑弹框控制
const isEdit = ref(false);
const openEdit = () => { isEdit.value = true };
const closeEdit = () => { isEdit.value = false };
const confirmEdit = () => {
    console.log('编辑成功');
    isEdit.value = false;
    isEditP.value = true
};
const isEditP = ref(false);
const closeEditP = () => { isEditP.value = false };
const confirmEditP = async (formEl: FormInstance | undefined, ruleForm: RuleForm) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            $UpdateDoctor(ruleForm).then(res => {
                if (res.code == 0) {
                    ElMessage({
                        message: '编辑成功',
                        type: 'success',
                    })
                    $DoctorList().then(res => {
                        doctor.value = res.data;
                    })
                    isEditP.value = false
                } else {
                    ElMessage({
                        message: '编辑失败',
                        type: 'error',
                    })
                }
            })
        } else {
            console.log('传输失败', fields)
        }
    })
};

//删除弹框控制
const isDelete = ref(false);
const openDelete = () => { isDelete.value = true };
const closeDelete = () => { isDelete.value = false };
const confirmDelete = () => {
    $DeleteDoctor(selected.value).then(res => {
        if (res.code == 0) {
            ElMessage({
                message: '删除成功',
                type: 'success',
            })
            $DoctorList().then(res => {
                doctor.value = res.data;
            })
            isDelete.value = false
        } else {
            ElMessage({
                message: '删除失败',
                type: 'error',
            })
        }
    })
};

//分页
const currentPage = ref(1); //当前页码
const pageSize = ref(5); //每页显示条数
const changePage = computed(() => {
    return filteredDoctor.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value)
});
</script>

<template>
    <div class="manager">
        <div class="manager-top">
            <el-button type="primary" plain @click="openAdd">
                <el-icon>
                    <IEpPlus />
                </el-icon>
                新增
            </el-button>
            <el-button type="success" plain @click="openEdit" :disabled="!(selected.length === 1)">
                <el-icon>
                    <IEpEdit />
                </el-icon>
                编辑
            </el-button>
            <el-button type="danger" plain @click="openDelete" :disabled="selected.length === 0">
                <el-icon>
                    <IEpDelete />
                </el-icon>
                删除
            </el-button>
            <div class="manager-search">
                <el-input placeholder="请输入医生相关信息" v-model="searchQuery" :suffix-icon="Search" size="mini">
                </el-input>
            </div>
        </div>
        <div class="manager-body">
            <table>
                <thead>
                    <tr>
                        <th width="40">
                            <input type="checkbox" v-model="selectAll" @change="toggleSelectAll">
                        </th>
                        <th>账号</th>
                        <th width="60">姓名</th>
                        <th>头像</th>
                        <th width="85">职位</th>
                        <th width="50">科室</th>
                        <th>擅长</th>
                        <th>自我介绍</th>
                        <th width="180">预约时间（星期/时间）</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="doctor in changePage" :key="doctor.id">
                        <td>
                            <input type="checkbox" :value="doctor.id" v-model="selected">
                        </td>
                        <td>{{ doctor?.id }}</td>
                        <td>{{ doctor?.name }}</td>
                        <td>
                            <img :src="doctor?.url" alt="">
                        </td>
                        <td>{{ doctor?.position }}</td>
                        <td>{{ type[doctor?.department] }}</td>
                        <td>{{ doctor?.good }}</td>
                        <td>{{ doctor?.introduction }}</td>
                        <td>{{ doctor?.time }}</td>
                    </tr>
                </tbody>
            </table>
        </div>
        <div class="manager-bottom">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15]"
                :background="true" layout="sizes, prev, pager, next" :total="filteredDoctor.length" />
        </div>
        <!-- 添加弹框 -->
        <Prompt @close-modal="closeAdd" @confirm-modal="confirmAdd" text="确定要添加这个医生吗？" v-if="isAdd">
        </Prompt>
        <DoctorPrompt @close-modal="closeAddP" @confirm-modal="confirmAddP" text="添加" v-if="isAddP">
        </DoctorPrompt>
        <!-- 编辑弹框 -->
        <Prompt @close-modal="closeEdit" @confirm-modal="confirmEdit" text="确定要编辑医生信息吗？" v-if="isEdit">
        </Prompt>
        <DoctorPrompt @close-modal="closeEditP" @confirm-modal="confirmEditP" text="编辑" :id="selected[0]"
            v-if="isEditP">
        </DoctorPrompt>
        <!-- 删除弹框 -->
        <Prompt @close-modal="closeDelete" @confirm-modal="confirmDelete" text="移除医生后，历史数据将不可恢复，确定要移除吗？"
            v-if="isDelete">
        </Prompt>
    </div>
</template>

<style scoped lang="scss">
.manager {
    margin: 10px;
    margin-top: 20px;
    border: 1px solid #ccc;
    box-shadow: 2px 2px 3px 0 #eee;

    .manager-top {
        display: flex;
        border-bottom: 1px solid #ccc;
        padding: 14px 15px 7px;

        .el-icon {
            margin-right: 10px;
        }

        .manager-search {
            margin-left: 20px;
            color: #333;
        }
    }

    .manager-body {

        table {
            width: calc(100% - 35px);
            border-spacing: 0;
            border-collapse: collapse;
            margin: 15px 20px 20px;
            box-sizing: border-box;

            thead {
                tr {
                    border-bottom: 1px solid #e3e8ee;

                    th {
                        font-size: 12px;
                        color: #333;
                        background-color: #f1f8ff;
                        padding: 15px 10px;
                        text-align: left;
                        font-weight: 400;
                        border: none;
                    }
                }
            }

            tbody {
                tr {
                    border-bottom: 1px solid #e3e8ee;

                    td {
                        font-size: 12px;
                        color: #333;
                        background-color: #fff;
                        padding: 15px 10px;
                        border: none;

                        img {
                            width: 50px;
                        }
                    }
                }
            }
        }
    }

    .manager-bottom {
        padding-bottom: 20px;
        padding-left: 20px;
    }
}
</style>